package com.biboheart.adapter.support.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {
    private static ObjectMapper objectMapper = null;

    /**
     * 获取object mapper实例
     * @return 如果未创建则创建，返回实例
     */
    public static ObjectMapper getInstance() {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        }
        return objectMapper;
    }

    /**
     * 对象转json字符串
     * @param obj 要转换的对象
     * @return json字符串
     */
    public static String obj2json(Object obj) throws JsonProcessingException {
        return getInstance().writeValueAsString(obj);
    }

    /**
     * json字符串转对象
     * @param content json字符串
     * @param valueType 匹配的对象类
     * @param <T> 指定转换后的类型
     * @return 转换的对象，确定转换类型，如果转换失败返回null
     */
    public static <T> T json2objWithType(String content, Class<T> valueType) throws JsonProcessingException {
        return getInstance().readValue(content, valueType);
    }
}
